import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';

import { RequirePermission } from '@src/common/decorator/require-permission.decorator';
import { P } from '@src/common/const/permission.const';
import { PaginatedDataDto } from '@src/common/dto/paginated-data.resp.dto';

import { UserService } from './user.service';
import { UserCreateReqDto } from './dto/user-create.req.dto';
import { UserCreateRespDto } from './dto/user-create.resp.dto';
import { UserListReqDto } from './dto/user-list.req.dto';
import { UserListRespDto } from './dto/user-list.resp.dto';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  @RequirePermission(P.USER_CREATE)
  async create(@Body() dto: UserCreateReqDto) {
    const user = await this.userService.create(dto);
    return plainToInstance(UserCreateRespDto, user);
  }

  @Get()
  @RequirePermission(P.USER_LIST)
  async list(@Query() dto: UserListReqDto) {
    const [data, total] = await this.userService.list(dto);
    return PaginatedDataDto.of(
      plainToInstance(UserListRespDto, data),
      total,
      dto.page,
      dto.pageSize,
    );
  }
}
